const {exec,escape} = require('../db/mysql.js');


const getList = (author, keyword) =>{
	let sql = `select * from blogs where 1=1 `;
	if(author){
		sql += `and author = ${author} `;
	}
	if(keyword){
		sql += `and title like %${keyword}% `;
	}
	sql += `order by createtime desc;`;
	
	return exec(sql); 
};
const getDetail = (id) => {
	let sql = `select * from blogs where id=${id} `;
	return exec(sql).then(e=>{
		return e[0];
	});
	// return {
	// 	id:1,
	// 	title:"标题1",
	// 	content:"内容1",
	// 	author: "name11",
	// }
};
const newBlog = (blogData = {}) => {
	const title = blogData.title;
	const content = blogData.content;
	const author = blogData.author;
	const createtime = +new Date();
	let sql = `insert into blogs (title,content,author,createtime) values ('${title}','${content}','${author}','${createtime}');`;
	return exec(sql).then(insertData => {
		return {
			id: insertData.insertId
		};
	});
	// return {
	// 	id: 3
	// }
};

const updataBlog = (id, blogData = {}) => {
	// console.log("updata",id,blogData);
	// return true
	console.log(blogData);
	let title = blogData.title;
	let content = blogData.content;
	console.log(id,title,content);
	let sql = `update blogs set title='${title}', content='${content}' where id=${id};`;
	return exec(sql).then(e=>{
		console.log(e);
		if(e.affectedRows > 0){
			return true;
		}
		return false;
	});
};


const delBlog = (id,author) => {
	// console.log('删除博客:',id);
	// return true
	console.log(id,author);
	let sql = `delete from blogs where id='${id}' and author='${author}';`;
	return exec(sql).then(e=>{
		console.log(e);
		if(e.affectedRows > 0){
			return true;
		}
		return false;
	});
};
module.exports = {
	getList,
	getDetail,
	newBlog,
	updataBlog,
	delBlog
};